package com.own.system.controller;


import com.own.system.entity.Department;
import com.own.system.service.DepartmentService;
import com.own.system.utils.Result;
import com.own.system.vo.query.DepartmentQueryVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author anonymous
 * @since 2024-08-15
 */
@RestController
@RequestMapping("/api/department")
public class DepartmentController {
    @Resource
    private DepartmentService departmentService;

    /**
     * 查询部门列表
     *
     * @param departmentQueryVo 查询条件
     * @return
     */
    @GetMapping("/list")
    public Result list(DepartmentQueryVo departmentQueryVo) {
        //调用查询部门列表方法
        List<Department> departmentList = departmentService.findDepartmentList(departmentQueryVo);
        //返回数据
        return Result.ok(departmentList);
    }

    /**
     * 查询上级部门列表
     *
     * @return
     */
    @GetMapping("/parent/list")
    public Result getParentList() {
        //调用查询上级部门列表方法
        List<Department> departmentList = departmentService.findParentDepartment();
        //返回数据
        return Result.ok(departmentList);
    }

    /**
     * 添加部门
     *
     * @param department 部门
     * @return
     */
    @PostMapping("add")
    @PreAuthorize("hasAuthority('sys:department:add')")
    public Result add(@RequestBody Department department) {
        if (departmentService.save(department)) {
            return Result.ok().message("部门添加成功");
        }
        return Result.error().message("部门添加失败");
    }

    @CrossOrigin
    @PutMapping("update")
    @PreAuthorize("hasAuthority('sys:department:edit')")
    public Result update(@RequestBody Department department) {
        if (departmentService.updateById(department)) {
            return Result.ok().message("部门修改成功");
        }
        return Result.error().message("部门修改失败");
    }

    /**
     * 查询是否有子部门
     * PathVariable意思是路径参数
     *
     * @param id
     * @return
     */
    @GetMapping("/check/{id}")
    public Result check(@PathVariable Long id) {
        //调用查询是否有子部门方法
        if (departmentService.hasChildrenOfDepartment(id)) {
            return Result.exist().message("该部门存在子部门，不能删除");
        }
        //调用查询部门是否有用户方法
        if (departmentService.hasUserOfDepartment(id)) {
            return Result.exist().message("该部门存在用户，不能删除");
        }
        return Result.ok().success(false).message("该部门不存在子部门，可以删除");
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @CrossOrigin
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:department:delete')")
    public Result delete(@PathVariable Long id) {
        if (departmentService.removeById(id)) {
            return Result.ok().message("部门删除成功");
        }
        return Result.error().message("部门删除失败");
    }
}
